# -*- coding: UTF-8 -*-
import io
import os
import time
from urllib.request import urlopen

import cv2
import numpy
import numpy as np
from PIL import Image

from opencv_tool.HogGetter import makeHogForDir, getHogFeature2

# 计算的特征纬度，和HOG算法有关系
DIMEN = 144


class ImageTarget:

    def __init__(self, targetImg, x):
        self.targetImg = targetImg
        self.x = x
        self.recResult = ""


def split_image_lvfu(img):
    # if path.startswith("http"):
    #     img = read_ne_mg_4_opencv(path)
    # else:
    #     img = cv2.imread(path)

    cv2.threshold(img, 150, 255, cv2.THRESH_BINARY, img)
    t_width = img.shape[1]
    t_height = img.shape[0]

    black_img = filter_out(img.copy())

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    black_img = cv2.erode(black_img, kernel)

    cv2.imwrite("temp.png", black_img)
    bgrimg = cv2.imread("temp.png")

    bgrimg = cv2.cvtColor(bgrimg, cv2.COLOR_BGR2GRAY)
    contours, hierarchy = cv2.findContours(bgrimg, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

    targets = []

    for con in contours:
        box = cv2.boundingRect(con)  # x，y，w，h
        if box[2] < t_width and (box[3] > t_height * 1.0 / 2):
            target = black_img[box[1]:box[1] + box[3], box[0]:box[0] + box[2]]
            targets.append(ImageTarget(target, box[0]))

    return targets


def read_ne_mg_4_opencv(http_path):
    image_bytes = urlopen(http_path).read()
    im = Image.open(io.BytesIO(image_bytes))
    img = cv2.cvtColor(numpy.asarray(im), cv2.COLOR_RGB2BGR)
    return img


def filter_out(src_frame):
    if src_frame is not None:
        hsv = cv2.cvtColor(src_frame, cv2.COLOR_BGR2HSV)
        lower_val = np.array([0, 0, 0])
        upper_val = np.array([179, 255, 127])
        mask = cv2.inRange(hsv, lower_val, upper_val)
        mask_inv = cv2.bitwise_not(mask)
        return mask_inv


def rec_validate(mat):
    '''
    识别指定文件、路径的图片
    :param path:
    :return:
    '''
    images = split_image_lvfu(mat)  # 输入图像

    # # 初始化机器学习引擎

    paths = os.listdir("./ml_data")
    total_array = np.full(dimen, 0.0)
    list = []

    for p in paths:
        if not p.startswith("."):
            absPathParent = os.path.join(path, p)
            subFiles = os.listdir(absPathParent)
            # print(absPathParent, "size(" + str(len(subFiles)) + ")")
            for subfile in subFiles:
                if subfile.startswith("."):
                    continue
                try:
                    absFilePath = os.path.join(absPathParent, subfile)
                    list.append(absFilePath)
                    vector = getHogFeature(absFilePath)
                    total_array = np.vstack((total_array, vector))

                except Exception as eror:
                    print(absFilePath + "-*- err sample" + str(eror))

    total_array = np.delete(total_array, 0, axis=0)


    label_list = []
    labelMap = {}
    for l in list:
        fname = int(os.path.basename(l).split(".")[0])
        label_list.append(fname)
        labelMap[int(fname)] = l

    label_sample = np.array(label_list).astype(np.float32).reshape((len(label_list), 1))
    knn = cv2.ml.KNearest_create()
    knn.train(vec, cv2.ml.ROW_SAMPLE, label_sample)

    rec_result = []

    for img in images:
        newcomer = getHogFeature2(img.targetImg).reshape((1, DIMEN))
        _, results, neighbours, dist = knn.findNearest(newcomer, 1)
        lmp = labelMap[int(results)]
        this_result = str(os.path.basename(os.path.dirname(lmp)))
        img.recResult = this_result
        rec_result.append(img)

    def take_second(elem):
        return elem.x

    rec_result.sort(key=take_second, reverse=False)

    return rec_result


if __name__ == "__main__":

    pass